<template>
	<view class="app-components-goods-card bg-white e-radius-20 e-p-20">
		<view>
			<view class="e-flex e-flex-between" :class="'store-tlt' + cardType">
				<slot name="header">
					<view class="e-flex e-flex-1" v-if="store"
						@tap="jump(store.type === 2 ? '/pages/nearby/store/info' : '/pages/store/index', { id: store.id })">
						<template v-if="isRadio">
							<view class="e-m-r-28" v-if="!isCartEdit && isDisabledStore">
								<view class="img-58 scale-8">
									<image :src="$staticPath('classify/disabled_radio.png')" class="img-48" @tap.stop>
									</image>
								</view>
							</view>
							<radio class="e-m-r-28" v-else :color="AppSkin.primary" :checked="storeCheck"
								@tap.stop="$emit('checkStore', goodsList)" />
						</template>
						<view class="e-m-r-12" v-if="logoShow">
							<load-image mode="aspectFill" :size="['48rpx']" radius="10rpx" :src="store[storeKeys.logo]">
							</load-image>
						</view>
						<text class="fw-600">{{ store[storeKeys.name] }}</text>
						<view class="self-icon e-m-l-20" v-if="APP_HAS_OWN&&(store.storeHasOwn||store.hasOwn)">
							{{ $t('classify.自营') }}
						</view>
					</view>
				</slot>
				<slot name="statusText"></slot>
			</view>
			<view v-for="(gItem, gIndex) in list" :key="gIndex">
				<view class="goods-info e-flex e-flex-items-start" :class="'goods-info' + cardType">
					<template v-if="isRadio">
						<view class="e-m-r-28"
							v-if="!isCartEdit && ((isReselection && gItem.productSku!.stock === 0) || isLimit)">
							<view class="img-58 scale-8">
								<image :src="$staticPath('classify/disabled_radio.png')" class="img-48" @tap.stop>
								</image>
							</view>

						</view>
						<view v-else @tap.stop="$emit('checkCart', gItem)">
							<radio class="e-m-r-28" :color="AppSkin.primary" :checked="isCheck(gItem.id)" @tap.stop="$emit('checkCart', gItem)" />
						</view>
					</template>

					<view class="right-box e-flex-1"
						@tap="jump(goodsLink, { id: gItem.prodId||gItem.commodityId||gItem.serviceId })">
						<view class="e-m-r-20">
							<load-image mode="aspectFill" :size="['180rpx']" :src="getProperty(gItem, goodsKeys.image)">
							</load-image>
						</view>
						<view class="goods-right e-flex-column e-flex-items-start e-flex-between  e-flex-1">
							<view class="goods-tlt  e-m-b-10 e-flex e-flex-items-start e-flex-between ">
								<view class="e-line-2 e-flex-1"
									:class="{ 'c-9a': isTextColorChange(gItem as unknown as CartGoodsItem) }">
									{{ getProperty(gItem, goodsKeys.name) }}
								</view>
								<view class="e-m-l-30" v-if="cardType == 2">X{{ getProperty(gItem, goodsKeys.qry) }}
								</view>
							</view>
							<view class="e-flex e-flex-between" v-if="isReselection && gItem.productSku!.stock === 0">
								<text>{{ $t('cart.请重新选择商品规格') }}</text>
								<view class="reselection c-primary text-center e-font-26"
									@tap.stop="handleReselection(gItem.prodId, gItem.id)">
									{{ $t('cart.重选') }}
								</view>
							</view>
							<view class="e-flex e-flex-between" v-else-if="isLimit">
								<text>{{ $t('classify.限购') + $t('classify.件') }}</text>
							</view>

							<template v-else>
								<view class=" e-flex e-flex-between e-m-b-34 " :class="[isReselection&&'sku-box']" 
									@tap.stop="handleReselection(gItem.prodId, gItem.id,goodsList[gIndex].basketCount,getProperty(gItem, goodsKeys.skuId))">
									<text class="c-secondary">{{ getProperty(gItem, goodsKeys.skuName) }}</text>
									<view class="sku-box__icon" v-if="isReselection">
										<app-image src="arrow_right.png" :size="['16rpx']" />
									</view>
									
									
								</view>

								<view class="e-flex e-flex-between" style="width:100%">
									<view class="price " :class="[cardType == 1 ? 'c-red fw-600' : 'c-47']">
										{{$unitEn}}{{ getProperty(gItem, goodsKeys.price) }}
									</view>
									<view class="e-flex" @tap.stop>
										<e-number-box bgColor="#fff" color="#999999" integer v-if="isEditCount" :min="1"
											:max="gItem.productSku ? gItem.productSku.stock : 999999"
											v-model="goodsList[gIndex].basketCount" :asyncChange="true"
											@change="editCount($event, gItem as unknown as CartGoodsItem, gIndex)"></e-number-box>
										
									</view>
								</view>
							</template>
							<view class="e-flex e-p-b-20 e-p-r-20 e-p-t-10 c-placeholder e-font-24"
								v-if="gItem.orderRefundMsg ">
								<view class="e-p-r-10">
									{{$t('order.退款原因')}}:
								</view>
								<view class="e-flex-1">
									{{gItem.orderRefundMsg}}
								</view>
							</view>
						</view>
					</view>

				</view>

				<slot name="deduction" :goods="gItem"></slot>
			</view>
			<!-- 不可下单商品 -->
			<view class="no-can-list e-p-20" v-if="noList && noList.length" @tap="handleShowReason">
				<view class="e-flex e-font-24 e-m-b-20" style="color:#808080">
					<view class=" e-flex-1">
						<text>{{$t('classify.以下商品无法购买')}}</text>
						<text>（{{$t('cart.共')}} {{noList.length}} {{$t('classify.件')}}）</text>
					</view>
					<view class="e-flex">
						<text class="e-m-r-4">{{$t('classify.查看原因')}}</text>
						<app-image src="arrow_right.png" :size="['20rpx']" />
					</view>
				</view>
				<view class="">
					<scroll-view scroll-x="true" style="white-space: nowrap;">
						<view class="e-flex">
							<view class="no-can-list__item e-m-r-20" v-for="item in noList" :key="item.commoditySpecId">
								<load-image mode="aspectFit" :size="['100rpx']" :src="item.commodityUrl">
								</load-image>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

		</view>
		<slot name="storeCoupon">

		</slot>
		<slot name="orderVos"></slot>
	</view>
</template>
<script lang="ts">
	import {
		defineComponent
	} from 'vue'
	export default defineComponent({
		name: 'goods-card',
		// #ifdef MP-WEIXIN
		// 将自定义节点设置成虚拟的，更加接近Vue组件的表现
		options: {
			virtualHost: true
		},
		// #endif
	})
</script>
<script setup lang="ts">
	import { computed } from 'vue'
	import {
		APP_HAS_OWN
	} from '@/env'
	import type { StoreInfo, OrderGoods, CartGoodsItem, OrderItem } from '@/common/request/api'
	import { useInit } from '@/common/stores'
	import { storeToRefs } from 'pinia'
	import { useCurrentInstance } from '@/common/hooks'
	import { getProperty } from '@/common/utils'

	const props = withDefaults(defineProps<{
		// 店铺信息
		store?: Partial<StoreInfo> & Record<string, any>
		// 店铺信息的键值
		storeKeys?: {
			name : string
			logo : string
		}
		// 商品列表
		goodsList?: Array<Partial<OrderGoods['deputys'][0] & OrderItem & CartGoodsItem> & Record<string, any>>
		// 不可以下单的商品列表
		noCanList?: OrderGoods['deputys']
		// 超出闪送限购数量的商品列表
		exceedLimitList?: OrderGoods['deputys']
		// 商品信息的键值
		goodsKeys ?: {
			image : string
			skuName : string
			skuId : string
			price : string
			name : string
			qry : string
		}
		// 是否可以勾选店铺
		isRadio ?: boolean
		// 是否可以编辑商品数量
		isEditCount : boolean
		// 是否显示店铺logo
		logoShow ?: boolean,
		// 点击商品时跳转的地址
		goodsLink?: string,
		// 点击商品事件
		isJump?: boolean,
		// 1为购物车类型，2为订单商品展示类型，
		cardType?: string,
		// 是否显示重选规格，购物车专属
		isReselection ?: boolean
		// 是否显示限购，购物车专属
		isLimit ?: boolean
		// 是否为编辑购物车商品，购物车专属
		isCartEdit ?: boolean
		// 被勾选中的商品列表
		cartCheck : CartGoodsItem[]
	}>(), {
		storeKeys: () => ({
			name: 'name',
			logo: 'logo'
		}),
		goodsKeys: () => ({
			image: 'commodityUrl',
			skuName: 'commoditySpecName',
			skuId : 'skuId',
			price: 'deputyMoney',
			name: 'commodityName',
			qry: 'commodityCount'

		}),
		logoShow: true,
		isJump: true,
		cardType: '2',
	})

	const emits = defineEmits(['update:goodsList', 'showReason', 'editCount','reselection'])

	const ctx = useCurrentInstance()

	const { AppSkin } = storeToRefs(useInit())

	const list = computed<Array<Partial<OrderGoods['deputys'][0] & OrderItem & CartGoodsItem>>>({
		get() {
			return props.goodsList
		},
		set(v) {
			emits('update:goodsList', v)
		}
	})




	const isDisabledStore = computed(() => {
		let isAllReselection = props.goodsList?.findIndex(item => {
			return (item?.productSku?.stock || 0) > 0
		}) > 0;
		return (props.isReselection && isAllReselection) || props.isLimit
	})

	const normalGoodsList = computed<CartGoodsItem[]>(() => {
		return props.goodsList.filter(item => {
			return (item?.productSku?.stock || 0) > 0
		}) as unknown as CartGoodsItem[]
	})
	const cartNormalCheck = computed(() => {
		return props.cartCheck.filter(item => {
			if ('productSku' in item) {
				return item.productSku?.stock > 0
			}
			return false
		}).map(item => item.id)
	})
	// 勾选店铺
	const storeCheck = computed(() => {
		let tempList : string[] = []
		normalGoodsList.value.map(item => {
			if (cartNormalCheck.value.includes(item.id)) {
				tempList.push(item.id)
			}
		})
		return tempList.length === normalGoodsList.value.length ? true : false
	})
	const noList = computed(() => {
		let arr = []
		if (props.noCanList) {
			arr.push(...props.noCanList)
		}
		if (props.exceedLimitList) {
			arr.push(...props.exceedLimitList)
		}
		return arr
	})


	const isTextColorChange = (goods : CartGoodsItem) => {
		return (props.isReselection && goods.productSku && goods.productSku.stock === 0) || props.isLimit
	}
	// 跳转页面
	const jump = (url : string, params : Record<string, string | number | undefined>) => {
		if (props.isJump) {
			ctx.$goTo(url,  params)
		}
	}
	// 是否被勾选
	const isCheck = (val ?: string) => {
		return cartNormalCheck.value.includes(val || '')
	}
	// 编辑
	const editCount = (e : { value : number }, goods : CartGoodsItem, index : number) => {
		// if(productSku)
		list.value[index].basketCount = e.value
		emits('editCount', e.value, goods.id)
	}
	const handleShowReason = () => {
		emits('showReason', props.noCanList, props.exceedLimitList)
	}
	
	const handleReselection = (prodId:string,id:number,basketCount?:number,skuId?:string) => {
		emits('reselection', prodId,id,basketCount,skuId)
	}
</script>

<style lang="scss" scoped>
	@include appBem_b(components-goods-card) {
		.flex {
			display: flex;
		}

		.scale-8 {
			transform: scale(0.8);
		}

		.c-47 {
			color: #474f59;
		}

		.c-9a {
			color: #9a9a9a;
		}

		.store-tlt1 {
			padding: 34rpx 0rpx 8rpx 20rpx;
		}

		.store-tlt2 {
			margin-bottom: 30rpx;
		}

		.goods-info {
			box-shadow: 0px -2rpx 0px 0px #f3f3f3;
		}

		.goods-info1 {
			padding: 30rpx 24rpx 30rpx 20rpx;
		}

		.goods-info2 {
			padding: 30rpx 30rpx 30rpx 30rpx;
		}

		.right-box {
			display: flex;

			.goods-right {
				height: 100%;

				.goods-tlt {
					width:100%;
					color: #454545;
					line-height: 40rpx;
					height: 80rpx;
				}

				.price {
					@include fontH(32, 38);
				}

				.sku-box {
					padding:4rpx 10rpx;
					width:100%;
					background: #F7F7F7;
					border-radius: 4rpx;
					&__icon{
						transform: rotate(90deg);
					}
				}
			}
		}

		:deep(e-number-box__input) {
			margin: 0 !important;
		}

		:deep(.e-number-box) {

			>view,
			input {
				border: 1rpx solid #cfcfcf;

				&:first-child {
					border-right: none;
				}

				&:last-child {
					border-left: none;
				}
			}

			input {
				width: 76rpx !important;
			}
		}

		.reselection {
			width: 94rpx;
			height: 54rpx;
			border-radius: 40rpx;
			border: 2rpx solid var(--color-primary);
			line-height: 50rpx;
		}

		.no-can-list {
			background: #F2F2F2;
			border-radius: 10rpx;

			&__item {
				width: 100rpx;
				height: 100rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				overflow: hidden;

				.img {
					width: 100rpx;
					height: 100rpx;
				}
			}
		}
	}
</style>